package com.cyberx.slackspringbootstarter.service;

import static com.slack.api.model.block.Blocks.*;

import com.cyberx.slackspringbootstarter.properties.BotConfig;
import com.cyberx.slackspringbootstarter.properties.ChannelConfig;
import com.slack.api.Slack;
import com.slack.api.methods.SlackApiException;
import com.slack.api.model.block.LayoutBlock;
import java.io.IOException;
import lombok.extern.log4j.Log4j2;

@Log4j2
public class Api {
  private final Slack slackInstance;
  private final ChannelConfig channelConfig;
  private final BotConfig botConfig;

  public Api(Slack slackInstance, ChannelConfig channelConfig, BotConfig botConfig) {
    this.slackInstance = slackInstance;
    this.channelConfig = channelConfig;
    this.botConfig = botConfig;
  }

  /** 发送简单文本信息 */
  public void send(String message) {
    try {
      slackInstance
          .methods(botConfig.getToken())
          .chatPostMessage(req -> req.channel(channelConfig.getId()).text(message));
    } catch (SlackApiException requestFailure) {
      // Slack API responded with unsuccessful status code (= not 20x)
      log.error(requestFailure);
    } catch (IOException connectivityIssue) {
      // Throwing this exception indicates your app or Slack servers had a connectivity issue.
      log.error(connectivityIssue);
    }
  }

  public void send(LayoutBlock block) {
    try {
      slackInstance
          .methods(botConfig.getToken())
          .chatPostMessage(
              req ->
                  req.channel(channelConfig.getId()).text("show message").blocks(asBlocks(block)));
    } catch (IOException | SlackApiException e) {
      log.error(e);
    }
  }
}
